<template>
  <div class="yy-page yy-system-template_list">
    <div class="yy-page-search" v-if="showSearch">
      <WidgetForm ref="searchFormWidget" :option="{
        style: 'display: flex;',
        itemStyle: 'margin-right: 10px;margin-bottom: 0;align-items: center;'
      }" :form-fields="search.formFields" :form-buttons="search.formButtons" />
    </div>
    <div class="yy-page-header">
      <div class="yy-page-header_title">
        <el-button :disabled="!search.formData.deptId" color="#009688" @click="onOpenDialog()">创建计划</el-button>
        <span v-if="!search.formData.deptId" style="margin-left: 10px;color:#aaa; font-size: 14px; font-weight: normal;">选择科室后进行操作！</span>
      </div>
      <div class="yy-page-header_action">
        <right-toolbar @showSearch="onShowSearch" @queryTable="getListData"></right-toolbar>
      </div>
    </div>
    <div class="yy-page-data">
      <WidgetTable
          ref="tableDataRef"
          :is-loading="table.isLoading"
          :columns="table.columns"
          :data="table.data"
          :options="table.options"
          :formats="table.formats"
          :paging-data="table.paging"
      >
      </WidgetTable>
    </div>
    <ScheduleEdit ref="scheduleEditRef" @editCallback="onEditCallback"/>
    <ScheduleDevice ref="scheduleDeviceRef"/>
  </div>
</template>

<script setup lang="ts">
import {onBeforeMount, defineEmits, reactive, ref} from "vue";
import {TableColumn, WidgetFormField} from "@/model/Definition";
import {EnvConfig, formatDate} from "@/utils/index.js";

import {ElButton, ElMessage} from "element-plus";
import WidgetTable from "@/components/widget/WidgetTable.vue";
import {useRouter} from "vue-router";
import ScheduleEdit from "./ScheduleEdit.vue";
import ScheduleApi from "@/api/broadcast/schedule";
import ScheduleDevice from "./ScheduleDevice.vue";
import {BcScheduleModel} from "@/model/BcScheduleModel";
import WidgetForm from "@/components/widget/WidgetForm.vue";
import {BaseModel} from "@/model/BaseModel";
import {EmployeeModel} from "@/model/EmployeeModel";
import EmployeeApi from "@/api/system/empl";
import useUserStore from "@/store/modules/user";
import DepartSelector from "@/components/Business/DepartSelector.vue";

const router = useRouter()
const userStore = useUserStore()
const $emit = defineEmits({
  //
})
const loading = ref(false)
const search = reactive<{formFields: WidgetFormField[],formData: any, formButtons: any, modelInstance: BaseModel, searchApiFun:any}>({
  modelInstance: new EmployeeModel(),
  searchApiFun: EmployeeApi.listEmployee,
  formData: {
    deptId: userStore.deptId || null,
  },
  formFields: [
    {field: 'deptId', initVal: () => userStore.deptId || null, config: {select: {clearable: true}}, placeholder:'请选择科室', label: '所属科室', type: 'templateField', style:'width: 150px;', component: DepartSelector,
      atChange: ({deptId, depart}) => {
        search.formData.deptId = deptId
        getListData()
      }},
    {field: 'searchKey', config: {input: {clearable: true}}, placeholder:"请输入关键字", label: '关键字', type: 'text', style:'width: 200px;', atChange: (searchKey) => {
        search.formData.searchKey = searchKey
        getListData()
      }}
  ],
  formButtons: []
})
const table = reactive<{
  isLoading: boolean,
  paging: any,
  columns: TableColumn[],
  data: BcScheduleModel[],
  options?: any,
  formats?: any
}>({
  isLoading: false,
  columns: [
    {
      "field":"index",
      "label":"序号",
      "type": "index",
      "showable":true,
      "fixed": 'left',
      "align": 'center',
      "width": 45
    },
    {
      "field":"name",
      "label":"计划名称",
      "showable":true,
      "fixed": 'left',
    },
    {
      "field":"description",
      "label":"描述",
      "showable":true,
    },
    {
      "field":"action",
      "label":"操作",
      "width": 210,
      "showable":true,
      "align": 'center',
      "fixed": 'right'
    }
  ],
  paging: {
    isPaging: true,
    pageSize: +EnvConfig.pageSize,
    pageIndex: 1,
    total: 0,
    pageChange: (pageIndex: number) => {
      onPageChange(pageIndex)
    }
  },
  options: {
    highlight: true
  },
  data: [],
  formats: {
    'state': {
      textType:'text',
      typeFormat: BcScheduleModel.getStateType,
      labelFormat: BcScheduleModel.getStateLabel
    },
    'updateTime': {
      labelFormat:  (val) =>formatDate(val)
    },
    'action': {
      items: [
        {label: '分配设备', elType: 'button', value: 'activeDevice', atClick: (data: BcScheduleModel) => {
                scheduleDeviceRef.value.onShowDialog(data)
            }},
        {label: '编辑', elType: 'button', value: 'edit', atClick: (data: BcScheduleModel) => onOpenDialog(data)},
        {label: '删除',elType: 'button', value: 'delete',  confirm: {title: '您确定要删除该计划吗？', atConfirm: (data: BcScheduleModel) => onDelete(data)}}
      ]
    }
  }
})

const searchFormWidget = ref()
const scheduleEditRef = ref()
const scheduleDeviceRef = ref()
const tableDataRef = ref()
const showSearch = ref(true)

onBeforeMount(() => {
  getListData()
})

const onShowSearch = () => {
  showSearch.value = !showSearch.value
  tableDataRef.value.onWindowResize()
}

const getListData = (pageIndex: number = 1) => {
  table.isLoading = true
  ScheduleApi.listSchedule(search.formData.deptId, search.formData.searchKey, pageIndex, table.paging.pageSize).then((res: any) => {
    table.data = res.data
    table.paging = Object.assign({}, table.paging, {pageIndex: res.pageIndex, total: res.total})
    table.isLoading = false
  }, () => {
    table.isLoading = false
  })
}

const onOpenDialog = (data?: BcScheduleModel) => {
  scheduleEditRef.value.onShowDialog(search.formData.deptId, data)
}

const onDelete = (data: BcScheduleModel) => {
  ScheduleApi.deleteSchedule(data.id).then(() => {
    const index = table.data.findIndex(item => item.id === data.id);
    table.data.splice(index, 1)
    ElMessage.success({
      message: '删除成功',
      showClose: true
    })
  })
}

const onEditCallback = (data: BcScheduleModel) => {
  const index = table.data.findIndex(item => item.id === data.id);
  if (index < 0) {
    table.data.unshift(data)
  } else {
    table.data.splice(index, 1, data)
  }
}

const onPageChange = (pageIndex: number) => {
  if (pageIndex != table.paging.pageIndex) {
    getListData(pageIndex);
  }
}


</script>
<style scoped lang="scss">

  .yy-system-template_list {
      &-item {
        width: 20%;
        display: inline-flex;
        flex-direction: column;
        margin: 5px 5px;
        cursor: pointer;
        &-content {
          width: 100%;
          height: 0;
          padding-bottom: 50%;
          position: relative;
        }
      }
  }
</style>